package com.kwin.excel.handler;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.kwin.excel.annotation.ResponseExcel;
import com.kwin.excel.config.ExcelConfigProperties;
import com.kwin.excel.enhance.WriterBuilderEnhancer;
import com.kwin.excel.util.ExcelException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.ObjectProvider;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author : wangkai
 * @version V1.0
 * @Package com.kwin.excel.handler
 * @Description:
 * @date 2021年10月19日 10:53
 **/
public class SingleSheetWriteHandler extends AbstractSheetWriteHandler {
    
    public SingleSheetWriteHandler(ExcelConfigProperties configProperties,
        ObjectProvider<List<Converter<?>>> converterProvider, WriterBuilderEnhancer excelWriterBuilderEnhance) {
        super(configProperties, converterProvider, excelWriterBuilderEnhance);
    }
    
    /**
     * 是否支持
     *
     * @param obj
     * @return
     */
    @Override
    public boolean support(Object obj) {
        if (obj instanceof List) {
            List objList = (List) obj;
            return !objList.isEmpty() && !(objList.get(0) instanceof List);
        }
        else {
            throw new ExcelException("@ResponseExcel 返回值必须为List类型");
        }
    }
    
    /**
     * 写成对象
     *
     * @param obj             obj
     * @param response      输出对象
     * @param responseExcel 注解
     */
    @Override
    @SneakyThrows
    public void write(Object obj, HttpServletResponse response, ResponseExcel responseExcel) {
        List list = (List) obj;
        ExcelWriter excelWriter = getExcelWriter(response, responseExcel);
    
        // 有模板则不指定sheet名
        Class<?> dataClass = list.get(0).getClass();
        WriteSheet sheet = this.sheet(responseExcel.sheets()[0], dataClass, responseExcel.template(),
            responseExcel.headGenerator());
        excelWriter.write(list, sheet);
        excelWriter.finish();
    }
}
